package com.dongan.security;

import com.alibaba.druid.util.StringUtils;
import com.dongan.utils.JwtUtils;
import com.dongan.utils.ResponseUtil;
import com.dongan.utils.ResultResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName:TokenLogoutHandler
 * @Description:token退出处理器
 * @Author:longtao
 * @Date:2021/6/28
 * @Version:1.0
 */
public class TokenLogoutHandler implements LogoutHandler {
    private JwtUtils jwtUtils;

    public TokenLogoutHandler(JwtUtils jwtUtils) {
        this.jwtUtils = jwtUtils;
    }

    public TokenLogoutHandler() {
    }

    public ResultResponseUtil resultResponseUtil(ResultResponseUtil resultResponseUtil) {
        return resultResponseUtil;
    }

    /**
     * Causes a logout to be completed. The method must complete successfully.
     *
     * @param request        the HTTP request
     * @param response       the HTTP response
     * @param authentication the current principal details
     */
    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        //从handler获取token
        String token = request.getHeader("token");
        ResultResponseUtil resultResponseUtil = null;
        //若token不为空则去除token
        if (!StringUtils.isEmpty(token)) {
            try {
                //jwtUtils.removeToken(token);
                token="";
                resultResponseUtil = new ResultResponseUtil(true, "退出成功!");
                ResponseUtil.out(response,resultResponseUtil);
            } catch (Exception e) {
                resultResponseUtil = new ResultResponseUtil(false, "退出失败!");
                ResponseUtil.out(response,resultResponseUtil);
            }
            resultResponseUtil = new ResultResponseUtil(true, "退出成功!");
            ResponseUtil.out(response,resultResponseUtil);
        }

    }
}
